package com.example.movie.ui.home.tabs

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Rect
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.movie.R
import com.example.movie.common.constants.AppConstants
import com.example.movie.common.model.RequestResult
import com.example.movie.data.movie.factory.HomeViewModelFactory
import com.example.movie.data.movie.model.HomeViewModel
import com.example.movie.data.movie.model.vo.MovieListBeanVo
import com.example.movie.ui.cinema.GlideImageLoader
import com.example.movie.ui.home.adapter.MovieListAdapter
import com.youth.banner.BannerConfig
import com.youth.banner.Transformer
import kotlinx.android.synthetic.main.fragment_recommend.*
import java.util.concurrent.TimeUnit


class RecommendFragment : Fragment() {

    private val homeViewModel: HomeViewModel by viewModels(factoryProducer = { HomeViewModelFactory() })
    private val bannerMovieMap: Map<Int, Int> = hashMapOf()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_recommend, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        initBanner()
        initMovieList()
    }

    private fun initBanner() {
        //设置banner样式
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE)
        //设置图片加载器
        banner.setImageLoader(GlideImageLoader())
        //设置banner动画效果
        banner.setBannerAnimation(Transformer.DepthPage)
        //设置标题集合（当banner样式有显示title时）
        banner.setBannerTitles(listOf("紧急救援", "篮球火"))
        //设置自动轮播，默认为true
        banner.isAutoPlay(true)
        //设置轮播时间
        banner.setDelayTime(TimeUnit.SECONDS.toMillis(5).toInt())
        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.CENTER)
        banner.setOnBannerListener {
            Toast.makeText(requireContext(), "点击了$it", Toast.LENGTH_SHORT).show()
        }
        //设置图片集合
        banner.setImages(listOf(AppConstants.demoImage, AppConstants.demoImage))
        //banner设置方法全部调用完毕时最后调用
        banner.start()
    }

    override fun onStart() {
        super.onStart()
        banner.startAutoPlay()
    }

    override fun onStop() {
        super.onStop()
        banner.stopAutoPlay()
    }

    @SuppressLint("SetTextI18n")
    private fun initMovieList() {
        homeViewModel.loadHomeMovieData()

        hot_movie_list.apply {
            this.layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
            this.addItemDecoration(object : RecyclerView.ItemDecoration() {
                private val space: Int = 10
                override fun getItemOffsets(
                    outRect: Rect,
                    view: View,
                    parent: RecyclerView,
                    state: RecyclerView.State
                ) {
                    outRect.left = space
                    outRect.right = space
                    outRect.bottom = space
                    outRect.top = space
                }
            })

            homeViewModel.hotMovieDataVo.observe(viewLifecycleOwner, { result ->
                with(mutableListOf<String>()){
                   result.success?.let {
                       val titles = mutableListOf<String>()
                       for (i in 0 until 2){
                           this.add(AppConstants.STATIC_SOURCE_URL + it[i].cimg)
                           titles.add(it[i].movieName!!)
                       }
                       banner.setImages(this)
                       banner.setBannerTitles(titles)
                       banner.start()
                   }
                }

                notifyDataChange(result, context, this)
                hot_showing_count.text = "一共${result.success?.size}部"
            })
        }

        coming_soon_movie_list.apply {
            this.addItemDecoration(object : RecyclerView.ItemDecoration() {
                private val space: Int = 10
                override fun getItemOffsets(
                    outRect: Rect,
                    view: View,
                    parent: RecyclerView,
                    state: RecyclerView.State
                ) {
                    outRect.left = space
                    outRect.right = space
                    outRect.bottom = space
                    outRect.top = space
                }
            })

            this.layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)

            homeViewModel.comingSoonMovieDataVo.observe(viewLifecycleOwner, { result ->
                notifyDataChange(result, context, this)
                coming_showing_count.text = "一共${result.success?.size}部"
            })

        }
    }
}

private fun notifyDataChange(
    result: RequestResult<List<MovieListBeanVo>>,
    context: Context,
    view: RecyclerView
) {
    val items = mutableListOf<MovieListBeanVo>()
    val data = result.success
    data?.let {
        repeat(data.size) { idx ->
            items.add(
                MovieListBeanVo(data[idx].movieId, data[idx].movieName, data[idx].cimg),
            )
        }
        val baseAdaptor = MovieListAdapter(items, context)
        view.adapter = baseAdaptor
        baseAdaptor.notifyDataSetChanged()
    }

}